import { Component, OnInit } from '@angular/core';
import {InventoryService} from "../inventory.service";
// import {ReportService} from "../../report/report.service";
import {ActivatedRoute, Router} from "@angular/router";
import {ConfirmationService} from "primeng/primeng";
import {FormBuilder, Validators} from "@angular/forms";
import {PublicService} from "../../services/public.service";
import {EventBusService} from "../../services/event-bus.service";

@Component({
  selector: 'app-requisition-application',
  templateUrl: './requisition-application.component.html',
  styleUrls: ['./requisition-application.component.scss']
})
export class RequisitionApplicationComponent implements OnInit {
  showBorrowItems: boolean = false;
  cols;
  zh:any; // 汉化
  personalData = [];
  statusNames;
  submitRequiestData;
  queryModels;
  MaterialData;
  totalRecords;
  selectMaterial =[];
  brandoptions;
  inspections = [];
  newInspectionPlan;
  urgency;
  approver;
  windowSize;
  viewState;//保存当前的操作状态
  width;
  editDataSource = [];
  editInspections = [];
  borrowData = [];
  selectInsepections = [];
  updateRequestioncols;
  title = '领用申请';
  sid;
  colsDetail;
  qureyModel = {
    label:'',
    value:''
  };
  dataSource = [];
  constructor(private inventoryService: InventoryService,
              private router:Router,
              private route:ActivatedRoute,
              private confirmationService: ConfirmationService,
              private publicService: PublicService,
              fb:FormBuilder,
              private eventBusService: EventBusService
             ) {
            this.newInspectionPlan = fb.group({
              sid: [''],
              name: [''],
              department: [''],
              check: [''],
              type: ['', Validators.required],
              return_time: ['', Validators.required],
              urgency: ['', Validators.required],
              remarks: ['', Validators.required],
              approve_remarks: [''],
            });
  }

  ngOnInit() {

    this.viewState = 'apply'
    // 查询人员表格数据
    this.queryPersonList('');
    this.queryMeterial();
    this.cols = [
      {field: 'sid', header: '编号',editable:false},
      {field: 'name', header: '名称',editable:false},
      {field: 'catagory', header: '分类',editable:false},
      {field: 'brand', header: '品牌',editable:false},
      {field: 'model', header: '型号',editable:false},
      {field: 'specification', header: '规格',editable:false},
      {field: 'quantity', header: '数量',editable:true},
    ];
    this.colsDetail = [
      {field: 'sid', header: '编号',editable:false},
      {field: 'name', header: '名称',editable:false},
      {field: 'catagory', header: '分类',editable:false},
      {field: 'brand', header: '品牌',editable:false},
      {field: 'model', header: '型号',editable:false},
      {field: 'specification', header: '规格',editable:false},
      {field: 'application_quantity', header: '数量',editable:true},
      {field: 'quantity', header: '实际出库数量' ,editable:true},
    ];
    this.updateRequestioncols = [
      // {field: 'quantity', header: '数量',editable:true},
      {field: 'sid', header: '编号' ,editable:false},
      {field: 'name', header: '名称' ,editable:false},
      {field: 'catagory', header: '分类' ,editable:false},
      {field: 'brand', header: '品牌' ,editable:false},
      {field: 'model', header: '型号' ,editable:false},
      {field: 'specification', header: '规格' ,editable:false},
      {field: 'application_quantity', header: '申请数量' ,editable:false},
      {field: 'quantity', header: '实际出库数量' ,editable:true},
      {field: 'onhand_quantity', header: '当前库存' ,editable:false},
    ];
    this.zh = {
      firstDayOfWeek: 1,
      dayNames: [ "周一","周二","周三","周四","周五","周六","周日" ],
      dayNamesShort: [ "一","二","三","四","五","六","七" ],
      dayNamesMin: [ "一","二","三","四","五","六","七" ],
      monthNames: [ "一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月" ],
      monthNamesShort: [ "一","二","三","四","五","六","七","八","九","十","十一","十二" ],
    };
    this.statusNames = [
      {label: '领用', value: '领用'},
    ];
    this.submitRequiestData = {
      "sid": "",
      "type": this.statusNames[0]['value'],
      "create_time":this.inventoryService.getFormatTime(),
      "urgency": "",
      "remarks": "",
      "approver": "",
      "approver_pid": "",
      "approve_remarks": "",
      "org": '',
      "inventories": []
    }
    this.querylogin();
    this.route.queryParams.subscribe(params=>{
      this.viewState = 'apply';
      if(params['sid']&&params['state'] && params['title']){
        this.sid = params['sid'];
        this.title = params['title'];
        this.viewState = params['state'];
        this.inventoryService.outboundShow(params['sid']).subscribe(data=>{
          this.borrowData = data;
          console.log(this.borrowData);
          this.editDataSource = this.borrowData['inventories']?this.borrowData['inventories']:[];
          if(!this.editDataSource){
            this.editDataSource = [];
            this.editInspections =[];
            this.totalRecords = 0;
          }
          this.totalRecords = this.editDataSource.length;
          this.editInspections = this.editDataSource.slice(0,10);
        })
      }
    })
    // this.queryMaterialDate();
    }
  goBack() {
    this.borrowData['status'] = "";
    this.eventBusService.requstion.next(this.borrowData['status']);
    this.router.navigate(['../requestionOverview'], {relativeTo: this.route});
  }
  //查询登录人
  querylogin(){
    this.inventoryService.queryPersonal().subscribe(data=>{
      this.personalData = data;
      console.log(this.personalData)
      this.submitRequiestData['org'] = this.personalData['organization']
    });
  }
  // 查询人员表格数据
  queryPersonList(oid) {
    this.publicService.getPersonList(oid).subscribe(data => {
      // console.log(data);
      this.approver = data;
      this.approver = this.inventoryService.formatDropdownDatas(this.approver)
      this.submitRequiestData.approver = this.approver[0]['label'];
      // console.log(this.submitRequiestData.approver);
    });
  }
  // 提交
  addStorageSubmint(submitData,dataSource){
    let inventories = [];
    for(let i = 0;i<dataSource.length;i++){
      let temp = dataSource[i];
      let obj = {};
      obj['sid'] = temp['sid'];
      obj['pn'] = temp['pn'];
      obj['borrower'] = temp['borrower'];
      obj['borrower_pid'] = temp['borrower_pid'];
      obj['location'] = temp['location'];
      obj['location_id'] = temp['location_id'];
      obj['keeper'] = temp['keeper'];
      obj['keeprer_pid'] = temp['keeprer_pid'];
      obj['quantity'] = temp['quantity'];
      inventories.push(obj);
    }
    submitData.inventories = inventories;
    this.inventoryService.requestionAddDelivery(submitData).subscribe(()=>{
      this.router.navigate(['../requestionOverview'],{queryParams:{title:'领用总览'},relativeTo:this.route})
    },(err:Error)=>{
      let message ;
      if(JSON.parse(JSON.stringify(err)).status===504){
        message = '似乎网络出现了问题，稍后重试'
      }else{
        message =err
      }
      this.confirmationService.confirm({
        message: message,
        rejectVisible:false,
      })
    })
  };
//保存
  addDeviceSave(data){
    let inventories = [];
    for(let i = 0;i<this.dataSource.length;i++){
      let temp = this.dataSource[i];
      let obj = {};
      obj['sid'] = temp['sid'];
      obj['pn'] = temp['pn'];
      obj['location'] = temp['location'];
      obj['location_id'] = temp['location_id'];
      obj['keeper'] = temp['keeper'];
      obj['keeprer_pid'] = temp['keeprer_pid'];
      obj['quantity'] = temp['quantity'];
      inventories.push(obj);
    }
    data.inventories = inventories;
    this.inventoryService.queryRequesttionDeliverySave(data).subscribe(data=>{
      this.router.navigate(['../requestionOverview'],{queryParams:{title:'领用总览'},relativeTo:this.route})

    },(err:Error)=>{
      let message ;
      if(JSON.parse(JSON.stringify(err)).status===504){
        message = '似乎网络出现了问题，稍后重试'
      }else{
        message =err
      }
      this.confirmationService.confirm({
        message: message,
        rejectVisible:false,
      })
    })
  };
  //修改保存方法
  updateDeviceSave(submitData,dataSource){
    let inventories = [];
    for(let i = 0;i<dataSource.length;i++){
      let temp = dataSource[i];
      let obj = {};
      obj['pn'] = temp['pn'];
      obj['sid'] = temp['sid'];
      obj['location'] = temp['location'];
      obj['location_id'] = temp['location_id'];
      obj['keeper'] = temp['keeper'];
      obj['keeprer_pid'] = temp['keeprer_pid'];
      obj['quantity'] = temp['quantity'];
      obj['delivery_sid'] = temp['delivery_sid'];
      obj['borrower'] = temp['borrower'];
      obj['borrower_pid'] = temp['borrower_pid'];
      obj['return_quantity'] = temp['return_quantity'];
      obj['balance'] = temp['balance'];
      obj['name'] = temp['name'];
      obj['catagory'] = temp['catagory'];
      obj['supplier'] = temp['supplier'];
      obj['brand'] = temp['brand'];
      obj['model'] = temp['model'];
      obj['specification'] = temp['specification'];
      inventories.push(obj);
    }
    submitData.inventories = inventories;
    this.inventoryService.queryDeliveryMod(submitData).subscribe(data=>{
      this.router.navigate(['../requestionOverview'],{queryParams:{title:'领用总览'},relativeTo:this.route})
    },(err:Error)=>{
      let message ;
      if(JSON.parse(JSON.stringify(err)).status===504){
        message = '似乎网络出现了问题，稍后重试'
      }else{
        message =err
      }
      this.confirmationService.confirm({
        message: message,
        rejectVisible:false,
      })
    })
  };
  queryMeterial(){
    this.inventoryService.queryMaterialInfocater().subscribe(data =>{
      if(data['紧急度']){
        this.urgency = data['紧急度']
        this.urgency = this.inventoryService.formatDropdownData(this.urgency)
      }else{
        this.urgency = [];
      }
      this.submitRequiestData.urgency = this.urgency[0]['label'];
    });
  }
  deleteStorage(){
    for(let i = 0;i<this.selectInsepections.length;i++){
      for(let j = 0;j<this.dataSource.length;j++){
        if(this.selectInsepections[i]['sid']===this.dataSource[j]['sid']){
          this.dataSource.splice(j,1);
          this.totalRecords = this.dataSource.length;
          this.inspections = this.dataSource.slice(0,10);
          this.selectInsepections = [];
        }
      }
    }
  }
  updatedeleteStorage(){
    for(let i = 0;i<this.selectInsepections.length;i++){
      for(let j = 0;j<this.editDataSource.length;j++){
        if(this.selectInsepections[i]['sid']===this.editDataSource[j]['sid']){
          this.editDataSource.splice(j,1);
          this.totalRecords = this.dataSource.length;
          this.editInspections = this.editDataSource.slice(0,10);
          this.selectInsepections = [];
        }
      }
    }
  }
  loadCarsLazy(event) {
    //in a real application, make a remote request to load data using state metadata from event
    //event.first = First row offset
    //event.rows = Number of rows per page
    //event.sortField = Field name to sort with
    //event.sortOrder = Sort order as number, 1 for asc and -1 for dec
    //filters: FilterMetadata object having field as key and filter value, filter matchMode as value

    //imitate db connection over a network
    setTimeout(() => {
      if(this.dataSource) {
        this.inspections = this.dataSource.slice(event.first, (event.first + event.rows));
      }
    }, 0);
  }
  editloadCarsLazy(event) {
    setTimeout(() => {
      if(this.editDataSource) {
        this.editInspections = this.editDataSource.slice(event.first, (event.first + event.rows));
      }
    }, 0);
  }
  formSubmit(){
    if(this.viewState === 'apply'){
      this.addStorageSubmint(this.submitRequiestData,this.dataSource);
    }else if(this.viewState === 'update'){
      this.addStorageSubmint(this.borrowData,this.editDataSource);
    }
  }

  formSave(){
    if(this.viewState === 'apply'){
      this.addDeviceSave(this.submitRequiestData);
    }else if(this.viewState === 'update'){
      this.updateDeviceSave(this.borrowData,this.editDataSource);

    }

  }
  searchSuggest(searchText,name){
    this.qureyModel={
      label:name,
      value:searchText.query
    }
    for(let key in this.qureyModel){
      this.qureyModel[key]= this.qureyModel[key].trim()
    }
    this.inventoryService.queryInventory(this.qureyModel).subscribe(
      data=>{
        switch (name){
          case 'sid':
            this.brandoptions = data;
            console.log(this.brandoptions)
            break;
        }
      }
    )
  }
  addDev(metail){
    this.showBorrowItems = false;
    for(let i = 0;i<metail.length;i++){
      let temp  = metail[i];
      this.dataSource.push(temp)
      this.editDataSource.push(temp);
    }
    this.totalRecords = this.dataSource.length;
    this.totalRecords = this.editDataSource.length;
    this.inspections = this.dataSource.slice(0,10);
    this.editInspections = this.editDataSource.slice(0,10);
  }
  showAddStorageMask(){
    this.showBorrowItems = !this.showBorrowItems;
  }
  closeBorrowItemsMask(bool){
    this.showBorrowItems = bool;
  }
  //确认出库
  sureApproved(){
    let inventories = [];
    for(let i = 0;i<this.selectInsepections.length;i++){
      let temp = this.selectInsepections[i];
      inventories.push(temp)
    }
    let queryModel = {
      "sid":this.borrowData['sid'],
      "inventories":inventories
    }
    this.confirmationService.confirm({
      message: '确定出库吗?',
      rejectVisible:true,
      accept: () => {
        this.inventoryService.queryBorrowSure(queryModel).subscribe(()=>{
          this.borrowData['status'] = "";
          this.eventBusService.requstion.next(this.borrowData['status']);
          this.router.navigate(['../requestionOverview'],{relativeTo:this.route})
        },(err:Error)=>{
          this.confirmationService.confirm({
            message: err['message'],
            rejectVisible:false,
          })
        })
      },
      reject:() =>{}
    })
  }
}
